package com.gel.agent.tools;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ImageSearchTool {

    private static final String API_KEY = "BMfmeTCJfYcNH12VET78JrfvPKrbz6Fe9e8YMUN1eYFgUYaw3uS2gyLe";
    private static final String API_URL = "https://api.pexels.com/v1/search";

    @Tool(description = "search image from web")
    public String searchImage(@ToolParam(description = "search query keyword") String query){
        try{
            return String.join(",",searchImageTool( query));
        }catch (Exception e){
            return "error search image"+e.getMessage();
        }

    }

    public List<String> searchImageTool(String query){
        Map<String,String> headers = new HashMap<>();
        Map<String , Object> params = new HashMap<>();
//        请求头
        headers.put("Authorization",API_KEY);
//        请求参数
        params.put("query",query);
//        发送get请求
        String response = HttpUtil.createGet(API_URL)
                .addHeaders(headers)
                .form(params)
                .execute()
                .body();
//        解析响应
        return JSONUtil.parseObj(response)
                .getJSONArray("photos")
                .stream()
                .map(photoObj-> (JSONObject)photoObj)
                .map(photeObj->photeObj.getJSONObject("src"))
                .map(photo->photo.getStr("medium"))
                .filter(StrUtil::isNotBlank)
                .collect(Collectors.toList());

    }




}
